/*
 *  Copyright 2016 Jeroen Mols
 *  Update by lipeng
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.jmolsmobile.landscapevideocapture.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hongwu.landscapevideocameracustom.R;
import com.jmolsmobile.landscapevideocapture.preview.CapturePreview;

public class VideoCaptureView extends FrameLayout implements OnClickListener {

    //private ImageView mDeclineBtnIv;
    private ImageView mAcceptBtnIv;
    private RelativeLayout mRecordBtnIv;
    private ImageView mChangeCameraIv;
    private ImageView btnStart;// 开始录制按钮
    private ImageView btnStop;// 停止录制按钮
    private ImageView shangguang;//闪光
    private ImageView timerCount;//倒计时开始
    private ImageView timerImg;
    private TextView chongpai;  //重拍


    private SurfaceView mSurfaceView;
    //private ImageView mThumbnailIv;
    private TextView mTimerTv;
    private Handler customHandler = new Handler();
    private long startTime = 0L;

    private RecordingButtonInterface mRecordingInterface;
    private boolean mShowTimer;
    private boolean isFrontCameraEnabled;
    private boolean isCameraSwitchingEnabled;

    public VideoCaptureView(Context context) {
        super(context);
        initialize(context);
    }

    public VideoCaptureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public VideoCaptureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(Context context) {
        final View videoCapture = View.inflate(context, R.layout.view_videocapture, this);

        mRecordBtnIv = (RelativeLayout) videoCapture.findViewById(R.id.videocapture_recordbtn_rl);
        mAcceptBtnIv = (ImageView) videoCapture.findViewById(R.id.videocapture_acceptbtn_iv);
        //mDeclineBtnIv = (ImageView) videoCapture.findViewById(R.id.videocapture_declinebtn_iv);
        mChangeCameraIv = (ImageView) videoCapture.findViewById(R.id.change_camera_iv);
        btnStart = (ImageView) videoCapture.findViewById(R.id.recorder_start);
        btnStop = (ImageView) videoCapture.findViewById(R.id.recorder_stop);
        shangguang = (ImageView) videoCapture.findViewById(R.id.iv_video_shanguang);
        timerCount = (ImageView) videoCapture.findViewById(R.id.iv_video_time_start);
        timerImg = (ImageView) videoCapture.findViewById(R.id.iv_timer_start);
        chongpai = (TextView) videoCapture.findViewById(R.id.videocapture_chong_iv);

        mRecordBtnIv.setOnClickListener(this);
        mAcceptBtnIv.setOnClickListener(this);
        //mDeclineBtnIv.setOnClickListener(this);
        mChangeCameraIv.setOnClickListener(this);
        shangguang.setOnClickListener(this);
        timerCount.setOnClickListener(this);
        chongpai.setOnClickListener(this);

        //mThumbnailIv = (ImageView) videoCapture.findViewById(R.id.videocapture_preview_iv);
        mSurfaceView = (SurfaceView) videoCapture.findViewById(R.id.videocapture_preview_sv);

        mTimerTv = (TextView) videoCapture.findViewById(R.id.videocapture_timer_tv);
    }

    public void setRecordingButtonInterface(RecordingButtonInterface mBtnInterface) {
        this.mRecordingInterface = mBtnInterface;
    }

    public void setCameraSwitchingEnabled(boolean isCameraSwitchingEnabled) {
        this.isCameraSwitchingEnabled = isCameraSwitchingEnabled;
        mChangeCameraIv.setVisibility(isCameraSwitchingEnabled ? View.VISIBLE : View.INVISIBLE);
    }

    public void setCameraFacing(boolean isFrontFacing) {
        if (!isCameraSwitchingEnabled) return;
        isFrontCameraEnabled = isFrontFacing;

        //调转摄像头UI变化
//        mChangeCameraIv.setImageResource(isFrontCameraEnabled ?
//                R.drawable.ic_change_camera_back :
//                R.drawable.ic_change_camera_front);
    }

    public SurfaceHolder getPreviewSurfaceHolder() {
        return mSurfaceView.getHolder();
    }

    //开始前UI变化
    public void updateUINotRecording() {
        mRecordBtnIv.setSelected(false);
        mChangeCameraIv.setVisibility(allowCameraSwitching() ? VISIBLE : INVISIBLE);
        mRecordBtnIv.setVisibility(View.VISIBLE);
        mAcceptBtnIv.setVisibility(View.GONE);
        //mDeclineBtnIv.setVisibility(View.VISIBLE);
        shangguang.setVisibility(VISIBLE);
        timerCount.setVisibility(VISIBLE);
        //mThumbnailIv.setVisibility(View.GONE);
        chongpai.setVisibility(GONE);
        mSurfaceView.setVisibility(View.VISIBLE);
        mTimerTv.setVisibility(GONE);
    }

    private Runnable updateTimerThread = new Runnable() {
        public void run() {
            long timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
            int seconds = (int) (timeInMilliseconds / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            updateRecordingTime(seconds, minutes);
            customHandler.postDelayed(this, 1000);
        }
    };

    //开始UI变化
    public void updateUIRecordingOngoing() {
        mRecordBtnIv.setSelected(true);
        mRecordBtnIv.setVisibility(View.VISIBLE);
        mChangeCameraIv.setVisibility(View.GONE);
        mAcceptBtnIv.setVisibility(View.GONE);
        //mDeclineBtnIv.setVisibility(View.GONE);
        shangguang.setVisibility(GONE);
        timerCount.setVisibility(GONE);
        chongpai.setVisibility(GONE);
        //mThumbnailIv.setVisibility(View.GONE);
        mSurfaceView.setVisibility(View.VISIBLE);
        if (mShowTimer) {
            mTimerTv.setVisibility(View.VISIBLE);
            startTime = SystemClock.uptimeMillis();
            updateRecordingTime(0, 0);
            customHandler.postDelayed(updateTimerThread, 1000);
        }
    }

    //结束UI变化
    public void updateUIRecordingFinished(Bitmap videoThumbnail) {
        mRecordBtnIv.setVisibility(View.VISIBLE);
        mRecordBtnIv.setEnabled(false);
        mAcceptBtnIv.setVisibility(View.VISIBLE);
        mChangeCameraIv.setVisibility(View.GONE);
        shangguang.setVisibility(GONE);
        timerCount.setVisibility(GONE);
        //mDeclineBtnIv.setVisibility(View.VISIBLE);
        //mThumbnailIv.setVisibility(View.VISIBLE);
        //mSurfaceView.setVisibility(View.GONE);
        chongpai.setVisibility(VISIBLE);

        //这里把预览停留在了第一帧，不友好
//        if (videoThumbnail != null) {
//            mThumbnailIv.setScaleType(ScaleType.CENTER_CROP);
//            mThumbnailIv.setImageBitmap(videoThumbnail);
//        }
        customHandler.removeCallbacks(updateTimerThread);

    }

    @Override
    public void onClick(View v) {
        if (mRecordingInterface == null) return;

        if (v.getId() == mRecordBtnIv.getId()) {
            mRecordingInterface.onRecordButtonClicked();
        } else if (v.getId() == mAcceptBtnIv.getId()) {
            mRecordingInterface.onAcceptButtonClicked();
        } /*else if (v.getId() == mDeclineBtnIv.getId()) {
            mRecordingInterface.onDeclineButtonClicked();
        } */ else if (v.getId() == mChangeCameraIv.getId()) {
            isFrontCameraEnabled = !isFrontCameraEnabled;
            mChangeCameraIv.setImageResource(isFrontCameraEnabled ?
                    R.drawable.ic_change_camera_front : R.drawable.ic_change_camera_back);
            mRecordingInterface.onSwitchCamera(isFrontCameraEnabled);
        } else if (v.getId() == shangguang.getId()) {
            //闪光灯
            mRecordingInterface.onShangGuang();
        } else if (v.getId() == timerCount.getId()) {
            mRecordingInterface.onTimerCountStart();
        } else if (v.getId() == chongpai.getId()) {
            mRecordingInterface.onChongPai();
        }


    }

    public void showTimer(boolean showTimer) {
        this.mShowTimer = showTimer;
    }

    private void updateRecordingTime(int seconds, int minutes) {
        mTimerTv.setText(String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
    }

    private boolean allowCameraSwitching() {
        return CapturePreview.isFrontCameraAvailable() && isCameraSwitchingEnabled;
    }


    public void setBeginEndAnimation(boolean isBegin) {

        final View view;
        if (isBegin) view = btnStart;
        else view = btnStop;

        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.1f);
        animator.setDuration(450);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if (btnStart == view) {
                    btnStart.setVisibility(View.GONE);
                    btnStart.setAlpha(1.0f);
                    btnStop.setVisibility(View.VISIBLE);

                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                } else {
                    btnStop.setVisibility(View.GONE);
                    btnStop.setAlpha(1.0f);
                    btnStart.setVisibility(View.VISIBLE);
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        animator.start();
    }


    public void timerCountStartUpadateImg(int count) {
        if (count == 3) {
            mChangeCameraIv.setVisibility(GONE);
            mAcceptBtnIv.setVisibility(GONE);
            //mDeclineBtnIv.setVisibility(GONE);
            shangguang.setVisibility(GONE);
            timerCount.setVisibility(GONE);
            //mThumbnailIv.setVisibility(GONE);
            mSurfaceView.setVisibility(View.VISIBLE);
            mRecordBtnIv.setEnabled(false);
            timerImg.setVisibility(VISIBLE);
            timerImg.setImageResource(R.mipmap.img_video_time_03);
        } else if (count == 2) {
            timerImg.setImageResource(R.mipmap.img_video_time_02);
        } else if (count == 1) {
            timerImg.setImageResource(R.mipmap.img_video_time_01);
        } else if (count == 0) {
            mRecordBtnIv.setEnabled(true);
            timerImg.setVisibility(GONE);
        }
    }
}
